﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using IBS.Bll.AutoPayments;
using IBS.Model;
using IBS.ServiceContracts;

namespace IBS.Bll.Tools
{
    public class IBSHelper
    {
        private static ServicesFactory factory = new ServicesFactory();
        private static string _pathToSqlScript = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/SqlScripts");
        
        private static void ExecuteSqlScript(string fileName)
        {
            var sqlConnectionString = ConfigurationManager.ConnectionStrings["IbsTest"].ConnectionString;
            using (var sqlConnection = new SqlConnection(sqlConnectionString))
            {

                var script = "";
                var fullFileName = Path.Combine(_pathToSqlScript, fileName);
                var file = new FileInfo(fullFileName);
                using (var fileStrem = File.OpenRead(fullFileName))
                {
                    using (var rStream = new StreamReader(fileStrem, Encoding.Unicode))
                    {
                        script = rStream.ReadToEnd();
                    }
                }

                var commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);

                sqlConnection.Open();
                foreach (string commandText in commandStrings)
                {
                    if (commandText.Trim() != "")
                    {
                        var command = new SqlCommand(commandText, sqlConnection);
                        command.ExecuteNonQuery();
                    }
                }
                
            }
        }
        public static void ReCreateDataBase()
        {
            ExecuteSqlScript("new_db.sql");
            ExecuteSqlScript("FillShemaTable.sql");
        }
        public static void ClearAllTables()
        {
            ExecuteSqlScript("EmptyAllTables.sql");
        }

        public static void FillStreets()
        {
            ExecuteSqlScript("FillStreets.sql");
        }

        public static void FillCurrencies()
        {
            ExecuteSqlScript("FillCurrencies.sql");
        }
        
        public static void FillAddresses()
        {
           ExecuteSqlScript("FillAddresses.sql");
        }
        public static void FillClients()
        {
            var factory = new ServicesFactory();
            var clientService = factory.GetInstance<IKnowledgeBaseService>();
            var authorityService = factory.GetInstance<IAuthorityService>();
            var cardService = factory.GetInstance<ICardService>();

            var testClient = new IBS.Model.Client
            {
                FirstName = "Test",
                LastName = "Test",
                DateOfBirth = new DateTime(1990, 10, 2),
                PassportNumber = 7654321,
                PassportSeries = "MP"
            };
            clientService.CreateClient(testClient, 1, 1, "script");

            var user = authorityService.CreateUser(testClient.Id, authorityService.GetUnmatchedCodeCards().First(), "user",
                                         "123456", "user@gmail.com");

            authorityService.CreateAdmin("admin", authorityService.GetUnmatchedCodeCards().First(), "123456", "admin@gmail.com");
            authorityService.CreateOperator("operator", authorityService.GetUnmatchedCodeCards().First(), "123456", "operator@gmail.com");

            cardService.CreateNewCard(testClient, CardType.MasterCard, "script", 0m);
            //cardService.CreateNewCard(testClient, CardType.VisaClassic, "script", 100m);
          
        }

        public static void FillCodeCards()
        {
            ExecuteSqlScript("FIllCodeCards.sql");
        }
        public static void FillAssets()
        {
            ExecuteSqlScript("FillAccounts.sql");
            //And now we must create new balance for them
            factory.GetInstance<IOperationDayService>().UpdateClientBalances();
        }

        public static void FillPayments()
        {
            var paymentService = factory.GetInstance<IPaymentService>();
            //Erip

           
            paymentService.CreateEripPayment(@"<company>COSMOS</company><title>Cosmos - TV</title><fields><field regexp='^\w{7}$' display='Contract number' error='Contract number should be 7 characters long'></field></fields>");
            paymentService.CreateEripPayment(@"<company>COSMOS</company><title>Cosmos - Internet</title><fields><field regexp='^\w{7}$' display='Contract number' error='Contract number should be 7 characters long'></field></fields>");
          
            paymentService.CreateEripPayment(@"<company>Communal</company><title>Communal - Rent</title><fields><field regexp='^[A-Za-z]\w{9}$' display='Personal account' error='Personal account number should be 10 characters long'></field></fields>");
            paymentService.CreateEripPayment(@"<company>Communal</company><title>Communal - Electricity</title><fields><field regexp='^[A-Za-z]\w{9}$' display='Personal account' error='Personal account number should be 10 characters long'></field></fields>");
            paymentService.CreateEripPayment(@"<company>Communal</company><title>Communal - Gas</title><fields><field regexp='^[A-Za-z]\w{9}$' display='Personal account' error='Personal account number should be 10 characters long'></field></fields>");
            paymentService.CreateEripPayment(@"<company>Communal</company><title>Communal - Phone</title><fields><field regexp='^\d{7}|\d{3}-\d{2}-\d{2}$' display='Phone number' error='Phone number should have 7 digits'></field></fields>");
            paymentService.CreateEripPayment(@"<company>Communal</company><title>Communal - Intercome</title><fields><field regexp='^\w{1,50}$' display='City' error='City is invalid'></field><field regexp='^\w{1,50}$' display='Street' error='Street name is invalid'></field><field regexp='^\d{0,4}$' display='House' error='House number is invalid'></field><field regexp='^\d{0,3}$' display='Building' error='Building number is invalid'></field></fields>");
            paymentService.CreateEripPayment(@"<company>Communal</company><title>Communal - Security</title><fields><field regexp='^\w{1,50}$' display='City' error='City is invalid'/><field regexp='^\w{1,50}$' display='Street' error='Street name is invalid'/><field regexp='^\d{1,4}$' display='House' error='House number is invalid'/><field regexp='^\d{1,5}$' display='Appartment' error='Appartment number is invalid'/>	<field regexp='^\d{0,3}$' display='Building' error='Building number is invalid'/></fields>");
            paymentService.CreateEripPayment(@"<company>MTS</company><title>MTS</title><fields><field regexp='33|29|44' display='Code' error='Available codes are 33, 29, 44'></field><field regexp='^\d{7}|\d{3}-\d{2}-\d{2}$' display='Phone number' error='Phone number should have 7 digits'></field></fields>");
            paymentService.CreateEripPayment(@"<company>Velcom</company><title>Velcom</title><fields><field regexp='33|29|44' display='Code' error='Available codes are 33, 29, 44'></field><field regexp='^\d{7}|\d{3}-\d{2}-\d{2}$' display='Phone number' error='Phone number should have 7 digits'></field></fields>");
            paymentService.CreateEripPayment(@"<company>Life</company><title>Life</title><fields><field regexp='33|29|44' display='Code' error='Available codes are 33, 29, 44'></field><field regexp='^\d{7}|\d{3}-\d{2}-\d{2}$' display='Phone number' error='Phone number should have 7 digits'></field></fields>");
            paymentService.CreateEripPayment(@"<company>WebMoney</company><title>WebMoney</title><fields><field regexp='^[a-zA-Z]\w{8}$' display='Contract number' error='Contract number should have 9 characters starting with a letter'></field></fields>");
            paymentService.CreateEripPayment(@"<company>Belavia</company><title>Belavia - Ticket</title><fields><field regexp='^[a-zA-Z]{,50}$' display='Last Name' error='Invalid name'></field></fields>");
            paymentService.CreateEripPayment(@"<company>BSUIR</company><title>BSUIR</title><fields><field regexp='^\w{5,50}$' display='Student Id' error='Student Id should be at least 5 characters (50 maximum)'></field></fields>");
            paymentService.CreateEripPayment(@"<company>BSU</company><title>BSU</title><fields><field regexp='^\w{5,50}$' display='Student Id' error='Student Id should be at least 5 characters (50 maximum)'></field></fields>");
            

            //NoErip
            paymentService.CreatePayment(@"<company>SOLO</company><title>Solo - Internet</title><fields><field regexp='^\w{7}$' display='Contract number' error='Contract number should be 7 characters long'></field></fields>");
            paymentService.CreatePayment(@"<company>Nord</company><title>Nord - TV</title><fields><field regexp='^[A-Za-z]{5,10}$' display='Contract number' error='Contract number should be 5-10 letters long'></field></fields>");
        }

        public static void SetNewDay()
        {
            factory.GetInstance<IOperationDayService>().UpdateClientBalances();
            factory.GetInstance<IOperationDayService>().UpdateCurrencyRates();
        }

        public static void FillIbsAndErip()
        {
            ExecuteSqlScript("FillClients.sql");
        }

        public static void StartAutoPaymentProcessor()
        {


            var processor = new AutoPaymentProcessor(factory.GetInstanceInSingleContextScope<IAutoPaymentService>(),
                                                     factory.GetInstanceInSingleContextScope<ITransferService>());

        }
    }


}
